﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObjects;
using GT5RemoteMobile.Services;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace GT5RemoteMobile
{
    public partial class NewRaceStep2 : System.Web.UI.Page
    {
        protected string selectedTrack;
        protected string jsessionId;
        protected string psnid;
        protected List<string> friendIds= new List<string>();
        protected Dictionary<string, List<RemoteRaceDriver>> drivers;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["trackid"] != null)
                selectedTrack = Request.QueryString["trackid"];
            if (Session["jsessionid"] == null)
                Response.Redirect("default.aspx");
            psnid = (Session["psnUser"] as Profile).ID;
            jsessionId = Session["jsessionid"].ToString();

            bool success = false;
            int retryCount = 5;

            while (!success)
            {
                try
                {
                    if (retryCount == 0)
                        break;
                    SelectTrack();
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCount--;
                }
            }

            if (!success)
                Response.Redirect("default.aspx");
            
            this.drivers = new Dictionary<string, List<RemoteRaceDriver>>();
            friendIds.Add(psnid);
            GetDrivers driverUtil = new GetDrivers();
            driverUtil.jsessionId = jsessionId;

            success = false;
            retryCount = 5;

            List<RemoteRaceDriver> rrDrivers = new List<RemoteRaceDriver>();

            while (!success)
            {
                try
                {
                    if (retryCount == 0)
                        break;
                     rrDrivers = driverUtil.LookupDrivers(psnid);
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCount--;
                }
            }

            if (!success)
                Response.Redirect("default.aspx");

            
            drivers.Add(psnid, rrDrivers);

        }

        private void SelectTrack()
        {
            // hack to get a proper jsession id from gran-turismo.com
            HttpWebRequest profileRequest = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/gt5/user/" + psnid + "/remoterace/")) as HttpWebRequest;
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#if(DEBUG)
            //profileRequest.Proxy = new WebProxy("localhost", 8888);
#endif
            profileRequest.Method = "POST";
            StreamWriter writer = new StreamWriter(profileRequest.GetRequestStream());

            writer.Write("article_id=" + selectedTrack);
            writer.Close();
            profileRequest.CookieContainer = new CookieContainer();
            profileRequest.Headers.Add("Cookie", jsessionId);
            profileRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            profileRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            //foreach (string c in Request.Cookies)
            //{
            //    Cookie cookie = new Cookie(Request.Cookies[c].Name, Request.Cookies[c].Value, Request.Cookies[c].Path, Request.Cookies[c].Domain);
            //    profileRequest.CookieContainer.Add(cookie);
            //}
            using (HttpWebResponse response = profileRequest.GetResponse() as HttpWebResponse)
            {
                // don't think we need anything from the response...may want to load the car list
            }
        }
    }
}